package jmine.tec.datadigester.positional.writer;

import java.lang.reflect.InvocationTargetException;

import jmine.tec.datadigester.positional.meta.PositionalFieldMetadata;

import org.apache.commons.beanutils.BeanUtils;

import bancosys.tec.datadigester.DataDigesterException;

/**
 * Abstração para {@link PositionalFieldWriter} que precisam guardar o método e a anotação processada
 * 
 * @author israel.crisanto
 * @param <T> anotação de layout positional
 */
public abstract class AbstractPositionalFieldWriter<T extends PositionalFieldMetadata> implements PositionalFieldWriter {

    private final T fieldMetadata;

    /**
     * Constructor
     * 
     * @param fieldMetadata fieldMetadata
     */
    public AbstractPositionalFieldWriter(T fieldMetadata) {
        this.fieldMetadata = fieldMetadata;
    }

    /**
     * {@inheritDoc}
     */
    public void writeToBean(Object bean, String line) {
        try {
            BeanUtils.setProperty(bean, this.fieldMetadata.name(), this.read(line));
        } catch (IllegalAccessException e) {
            throw new DataDigesterException(e);
        } catch (InvocationTargetException e) {
            throw new DataDigesterException(e);
        }
    }

    /**
     * Reads a value from the given line
     * 
     * @param line line
     * @return value
     */
    public abstract Object read(String line);

    /**
     * @return field metadata
     */
    protected T getFieldMetadata() {
        return this.fieldMetadata;
    }
}
